package club.controller;

import club.pojo.Apply;
import club.service.ApplyService;
import club.util.Message;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;


@Controller
@RequestMapping("/apply")
public class ApplyController {

    @Resource
    private ApplyService applyService;

    /**
     * 分页查询申请列表
     * @param state 申请状态（可选，用于筛选）
     * @param pageNum 页码
     * @return 包含分页信息的操作结果消息
     */
    @RequestMapping("/applys")
    @ResponseBody
    public Message apply(@RequestParam(required = false) Integer state, @RequestParam("pn") Integer pageNum) {
        Integer pageSize = 3;
        if (pageNum == 0) {
            pageNum = 1;
        }
        // 调用服务层获取分页数据，根据状态筛选
        PageInfo<Apply> apply = applyService.allApply(state, pageNum, pageSize);
        return Message.success().add("pageInfo", apply);
    }

    /**
     * 根据ID查找申请
     * @param id 申请ID
     * @return 包含申请信息的操作结果消息
     */
    @RequestMapping("/findById")
    @ResponseBody
    public Message findByid(Integer id) {
        Apply byid = applyService.findByid(id);
        // 调用服务层查找申请
        return Message.success().add("apply", byid);
    }

    /**
     * 更新申请信息
     * @param apply 包含更新信息的申请对象
     * @return 操作结果消息
     */
    @RequestMapping("/update")
    @ResponseBody
    public Message update(Apply apply) {
        int i = applyService.updateApply(apply);
        if (i > 0) {
            return Message.success();
        }
        return Message.fail();
    }

    /**
     * 删除申请
     * @param id 申请ID
     * @return 操作结果消息
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Message delete(Integer id) {
        int i = applyService.del(id);
        if (i > 0) {
            return Message.success();
        } else {
            return Message.fail();
        }
    }

    /**
     * 创建新申请
     * @param apply 申请对象
     * @return 操作结果消息
     */
    @RequestMapping("/create")
    @ResponseBody
    public Message create(Apply apply) {
        apply.setApplyTime(new Date());
        apply.setState(2);
        Integer integer = applyService.create(apply);
        if (integer > 0) {
            return Message.success();
        } else {
            return Message.fail();
        }
    }
}